#!/usr/bin/python
# -*- coding: utf-8 -*-
#apkpyanidb.py
#0.01 - 17.03.08 - Работает! Определяет для файла релиз группы
import socket,os,re,sys
from Crypto.Hash.MD4 import new as md4

'''
пытаемся общацца с AniDB
http://wiki.anidb.net/w/UDP_API_Definition#Server_.2F_UDP_Connection
http://dev.jvnv.net/misc/file/trunk/pyanidb/pyanidb/__init__.py
http://www.python.org/doc/current/lib/module-socket.html
'''

HOST='api.anidb.info'
PORT=9000
login='apkawa'
password='xerosexo'

file=sys.argv[1]

class anidb:
    def __init__(self):
        self.sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind(('0.0.0.0', 1234))
        self.sock.connect((HOST,PORT))
    def close(self):
        self.sock.send('LOGOUT s=%s'%self.session)
        print self.sock.recv(1024)
        self.sock.close()
    def auth(self,login,password):
        self.sock.send('AUTH user=%s&pass=%s&protover=3&client=pyanidb&clientver=0'%(login,password))
        self.session=self.sock.recv(1024).split()[1]
        return self.session
    def findfile(self,file):
        self.ed2k=ed2k_hash(file)
        self.sock.send('FILE size=%s&ed2k=%s&s=%s'%(self.ed2k[0],self.ed2k[1],self.session))
        return parsed_reliz(self.sock.recv(1024).split('|')[-1])


def ed2k_hash(file): #Говорим спасибо OXIj за алгоритм
    block_size=9728000

    f=open(file, "rb")
    f.seek(0, 2)
    size = f.tell()
    f.seek(0, 0)

    chunks = (size // block_size) + 1
    if (size % block_size) == 0: chunks -= 1

    if chunks <= 1:
        return md4(f.read()).hexdigest()

    result_hashes = ""
    for _ in range(0, chunks):
        result_hashes += md4(f.read(block_size)).digest()
    return size, md4(result_hashes).hexdigest()

def parsed_reliz(namefile):
    group=re.findall('\[.+?\]',namefile)[0]
    return group

a=anidb()
a.auth(login, password)
print a.findfile(file)
a.close()
